import fs from 'fs';
import yaml from 'yaml';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前目录的绝对路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * 同步喵喵帮助，将 ../../miao-plugin/config/help.js 转换为 ../config/help.yaml
 */
async function syncMiaoMiaoHelpToYaml() {
    // 定义路径
    const _path = process.cwd();
    const jsFilePath = path.resolve(_path, 'plugins/miao-plugin/config/help.js');
    const defaultJsFilePath = path.resolve(_path, 'plugins/miao-plugin/config/help_default.js');
    const yamlFilePath = path.resolve(_path, 'plugins/help-plugin/config/help.yaml');
    const backupFilePath = `${_path}/plugins/help-plugin/config/help_backup_${Date.now()}.yaml`;

    try {
        // 选择文件路径
        let filePathToUse = jsFilePath;
        if (!fs.existsSync(jsFilePath)) {
            console.warn(`指定的帮助文件 ${jsFilePath} 不存在，使用默认帮助文件 ${defaultJsFilePath}。`);
            filePathToUse = defaultJsFilePath;
        }

        // 备份现有的 YAML 文件
        if (fs.existsSync(yamlFilePath)) {
            fs.copyFileSync(yamlFilePath, backupFilePath);
            console.log(`成功备份现有的 help.yaml 到 ${backupFilePath}`);
        }

        // 动态导入 JS 文件内容
        const module = await import(`file://${filePathToUse}`);
        const helpConfig = module.default || module;

        // 转换为简化的 YAML 格式
        const simplifiedHelpConfig = helpConfig.helpList.map(group => ({
            group: group.group,
            desc: group.desc || undefined,
            list: group.list.map(item => ({
                icon: 'paimon',
                title: item.title,
                desc: item.desc
            }))
        }));

        // 将简化后的 JavaScript 对象转换为 YAML 格式
        const yamlContent = yaml.stringify(simplifiedHelpConfig);

        // 将 YAML 内容写入文件
        fs.writeFileSync(yamlFilePath, yamlContent, 'utf8');
        console.log(`成功将 ${filePathToUse} 同步到 ${yamlFilePath}`);
    } catch (error) {
        console.error('同步过程中出现错误:', error);
    }
}

export default syncMiaoMiaoHelpToYaml;
